package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        //  让客户端与服务器建立连接
        socket = new Socket(serverIP,serverPort);
    }

    public void start(){
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerFromSocket = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while (true){
                // 输入数据
                System.out.println();
                System.out.printf("->");
                String request = scanner.next();
                // 发送请求
                printWriter.println(request);
                printWriter.flush();
                // 等待响应
                String response = scannerFromSocket.next();

                // 打印响应
                System.out.printf("request:%s   response:%s",request,response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        //  因为客户端，服务端都在同一个电脑上 所以用127.0.0.1
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
